package org.jederik.studip.android.view;

import org.jederik.android.provider.StudIP;
import org.jederik.android.provider.StudIP.Feed;
import org.jederik.android.provider.StudIP.Messages;
import org.jederik.studip.android.R;
import org.jederik.studip.android.view.tools.ResourceActivity;
import org.jederik.studip.android.view.tools.FormatHelper;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

/**
 * Diese Activity zeigt eine Nachricht an.
 * @author Jann-Frederik Laß
 *
 */
public class ViewMessage extends ResourceActivity {
	
	private Cursor cursor = null;
	
	@Override
	public void initView() {
		// Layout laden:
		setContentView(R.layout.view_message_table);
	}
	
	@Override
	public void showData(Cursor cursor) {
		
		if (cursor == null || cursor.isClosed() || !cursor.moveToFirst()) {
			return;
		}

		// Betreff in Betreffzeile einfügen:
		TextView subject = (TextView) findViewById(R.id.subject);
		subject.setText(cursor.getString(cursor.getColumnIndex(Messages.SUBJECT)));
		
		// Absender in Absendertzeile einfügen:
		TextView author = (TextView) findViewById(R.id.author);
		author.setText(cursor.getString(cursor.getColumnIndex(Messages.AUTHOR)));
		
		// Formatiertes Datum in Datumszeile einfügen:
		TextView date = (TextView) findViewById(R.id.date);
		String timestamp = cursor.getString(cursor.getColumnIndex(Feed.DATE));
		if (timestamp==null) timestamp = "0";
		date.setText(FormatHelper.formatDate(Integer.parseInt(timestamp)));
		
		// Nachricht in Nachrichtenfeld einfügen:
		TextView text = (TextView) findViewById(R.id.text);
		text.setText(cursor.getString(cursor.getColumnIndex(Messages.TEXT)));
		

		// Inhalt merken:
		this.cursor = cursor;
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		// Menü laden:
		MenuInflater mi = new MenuInflater(getApplication());
		mi.inflate(R.menu.view_message, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent i;
		switch (item.getItemId()) {
		case R.id.answer:
			
			// Intent zum senden einer Nachricht erzeugen:
			Uri uri = Messages.CONTENT_URI;
			i = new Intent(Intent.ACTION_SEND, uri);
			
			i = new Intent(this, SendMessage.class);
			
			// Felder recipient und subject setzen:
			cursor.moveToFirst();
			i.putExtra("recipient", cursor.getString(cursor.getColumnIndex("author_uname")));
			i.putExtra("subject", "Re: " + cursor.getString(cursor.getColumnIndex("subject")));
			
			// Activity starten:
			startActivity(i);
			
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}

	@Override
	public String getType() {
		return StudIP.TYPE_MESSAGE;
	}

	@Override
	public String getId() {
		return getIntent().getData().getLastPathSegment();
	}

	@Override
	public boolean canBeVisited() {
		return true;
	}
}
